package com.tyrone.concurrent.basic;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;

/**
 * 管道输入/输出流
 * 通过 PipedWriter.connect(PipedRead) 连接输出流和输入流，实现线程之间的通信
 * @author xieyl
 * @create 2021/12/3 18:07
 */
public class Piped {
    public static void main(String[] args) throws IOException {
        PipedWriter out = new PipedWriter();
        PipedReader in = new PipedReader();
        out.connect(in);
        Thread thread = new Thread(new Print(in), "PrintThread");
        thread.start();
        int receive = 0;
        try{
            while ((receive=System.in.read())!=-1 ){
                out.write(receive);
            }
        }finally {
            out.close();
        }
    }

    static class Print implements Runnable {
        private PipedReader in;

        public Print(PipedReader in) {
            this.in = in;
        }

        @Override
        public void run() {
            int receive = 0;
            try {
                while ((receive = in.read()) != -1){
                    System.out.print((char) receive);
                }
            } catch (Exception e) {

            }
        }
    }
}
